package demo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ASUS
 * Date: 2025-02-19
 * Time: 16:34
 */

class MyBlockingQueue {
    private String[] items = new String[1000];

    volatile int head = 0;

    volatile int tail = 0;

    volatile int size = 0;

    public void put(String elem) throws InterruptedException {
        synchronized(this) {
            while (size >= items.length) {
                //return;
                this.wait();
            }
            items[tail] = elem;
            tail++;
            if (tail >= items.length) {
                tail = 0;
            }
            size++;
            this.notify();
        }
    }


    public String take() throws InterruptedException {
        synchronized(this) {
            while (size == 0) {

                // return null;
                this.wait();
            }
            String elem = items[head];
            head++;
            if (head >= items.length) {
                head = 0;
            }
            size--;
            this.notify();
            return elem;
        }
    }

}
public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue queue = new MyBlockingQueue();
//        queue.put("aaa");
//        queue.put("bbb");
//        queue.put("ccc");
        Thread t1 = new Thread(() -> {
           int count = 0;
           while (true) {
               try {
                   queue.put(count + "");
                   System.out.println("生产元素:" + count);
                   count++;

                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                String count = null;
                try {
                    count = queue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("消费元素:" + count);
            }

        });

        t1.start();
        t2.start();


    }
}
